package com.cb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cb.common.CustomException;
import com.cb.entity.Category;
import com.cb.entity.Dish;
import com.cb.entity.Setmeal;
import com.cb.mapper.CategoryMapper;
import com.cb.service.CategoryService;
import com.cb.service.DishService;
import com.cb.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    @Lazy
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    @Override
    public IPage<Category> getCategory(Page<Category> categoryPage) {
        //构造条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加排序条件，根据sort进行排序
        queryWrapper.orderByAsc(Category::getSort);
        //进行分页查询
        Page<Category> page = baseMapper.selectPage(categoryPage, queryWrapper);
        return page;
    }

    @Override
    public void remove(Long ids) {
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件，根据分类id进行查询
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,ids);
        long dishCount = dishService.count(dishLambdaQueryWrapper);
        //查询当前分类是否关联菜品,如果已经关联，抛出业务异常
        if(dishCount>0){
            //已经关联菜品，抛出业务异常
            throw new CustomException("已经关联菜品，不能删除！");
        }

        //查询当前分类是否关联了套餐，如果已经关联，抛出业务异常
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件，根据分类id进行查询
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,ids);
        long setmealCount = setmealService.count(setmealLambdaQueryWrapper);
        if(setmealCount>0){
            //已经关联套餐，抛出业务异常
            throw new CustomException("已经关联套餐，不能删除！");
        }
        removeById(ids);
    }

    @Override
    public List<Category> getList(Category category) {
        //条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        queryWrapper.eq(category.getType()!=null,Category::getType,category.getType());
        //添加排序条件
        queryWrapper.orderByAsc(Category::getSort).orderByAsc(Category::getUpdateTime);
        List<Category> list = list(queryWrapper);
        return list;
    }
}